package com.wangp.mywrite.s_netty.chat_group.client;

import cn.hutool.system.RuntimeInfo;
import com.wangp.mywrite.s_netty.chat_group.message.RpcRequestMessage;
import com.wangp.mywrite.s_netty.chat_group.protocol.MessageCodecSharable;
import com.wangp.mywrite.s_netty.chat_group.protocol.ProtocolFrameDecoder;
import com.wangp.mywrite.s_netty.chat_group.protocol.SequenceIdGenerator;
import com.wangp.mywrite.s_netty.chat_group.server.handler.RpcResponseMessageHandler;
import com.wangp.mywrite.s_netty.chat_group.server.service.HelloService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;

import java.lang.reflect.Proxy;

@Slf4j
public class RpcClientManager {

    public static void main(String[] args) {
        HelloService proxyService = getProxyService(HelloService.class);
        System.out.println(proxyService.sayHello("张三"));
//        System.out.println(proxyService.sayHello("李四"));
//        System.out.println(proxyService.sayHello("wangwu"));
    }

    private static Channel channel = null;
    private static final Object LOCK = new Object();

    // 创建代理类
    public static <T> T getProxyService(Class<T> serviceClass) {
        ClassLoader classLoader = serviceClass.getClassLoader();
        Class<?>[] interfaces = new Class[]{serviceClass};
        Object o = Proxy.newProxyInstance(classLoader, interfaces, ((proxy, method, args) -> {
            // 1.将方法调用转换为消息对象
            int sequenceId = SequenceIdGenerator.nextId();
            RpcRequestMessage msg = new RpcRequestMessage(
                    sequenceId,
                    serviceClass.getName(),
                    method.getName(),
                    method.getReturnType(),
                    method.getParameterTypes(),
                    args
            );
            // 2.将消息对象发出去
            getChannel().writeAndFlush(msg);
            // 3. 准备一个空的 promise 接收对象               指定promise 对象异常接受结果线程
            DefaultPromise<Object> promise = new DefaultPromise<>(getChannel().eventLoop());
            RpcResponseMessageHandler.PROMISES.put(sequenceId,promise);
            // 4. 等待promise 结果
            promise.await();
            if(promise.isSuccess()){
                // 调用正常
                return promise.getNow();
            }else {
                // 调用异常
                Throwable cause = promise.cause();
                throw new RuntimeException(cause);
            }
        }));
        return (T) o;
    }


    // 获取channel
    public static Channel getChannel() {
        if (channel != null) {
            return channel;
        }
        synchronized (LOCK) {
            if (channel != null) {
                return channel;
            }
            initChannel();
            return channel;
        }
    }

    /**
     * 初始化 channel 方法
     */
    private static void initChannel() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        RpcResponseMessageHandler RPC_HANDLER = new RpcResponseMessageHandler();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProtocolFrameDecoder());
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    ch.pipeline().addLast(RPC_HANDLER);
                }
            });
            channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().addListener(future -> {
                group.shutdownGracefully();
            });
        } catch (Exception e) {
            log.error("client error", e);
        }
    }
}
